import 'dart:io';

import 'package:realmega_ota/realmega/running_log_manager.dart';
import 'package:realmega_ota/util/multi_output.dart';
import 'package:logger/logger.dart';
import 'package:path_provider/path_provider.dart';

class Log {
  static Logger _logger = Logger(
    filter: ProductionFilter(),
    printer: SimplePrinter(),
    output: ConsoleOutput()
  );

  static void init(){
    if(Platform.isAndroid){
      getExternalStorageDirectory().then((value) {
        _initLog(value!);
      });
    }else if(Platform.isIOS){
      getApplicationDocumentsDirectory().then((value) {
        _initLog(value);
      });
    }else{
      throw UnsupportedError('not support platform ${Platform.localeName}');
    }
  }

  static void _initLog(Directory value) {

    RunningLogManager.instance.addLog('初始化日志:${value.path}');
    value.exists().then((exist) {

      RunningLogManager.instance.addLog('初始化日志文件是否存在:${exist}');

      DateTime currentTime = DateTime.now();
      String date = '${currentTime.year}-${currentTime.month}-${currentTime.day}';

      if(exist) {
        _createLogDir(value, date);
      }else{
        value.create(recursive: true).then((dir) {
          _createLogDir(dir, date);
        }).onError((error, stackTrace){
          RunningLogManager.instance.addLog('初始化日志报错：$error');
        }).catchError((onError){
          RunningLogManager.instance.addLog('初始化日志异常:${onError}');
        });
      }
    });
  }

  static void _createLogDir(Directory dir, String date) {
    _logger = Logger(
        filter: ProductionFilter(),
        printer: SimplePrinter(),
        output: CustomMultiOutput(file: File('${dir.path}/log_$date.txt'))
    );
  }

  static void v(dynamic message) {
    _logger.v(message);
  }

  static void d(dynamic message) {
    _logger.d(message);
  }

  static void i(dynamic message) {
    _logger.i(message);
  }

  static void w(dynamic message) {
    _logger.w(message);
  }

  static void e(dynamic message) {
    _logger.e(message);
  }

  static void wtf(dynamic message) {
    _logger.wtf(message);
  }

  static void close(){
    _logger.close();
  }
}
